from rest_framework import mixins
from rest_framework import permissions, status
from rest_framework.decorators import permission_classes
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from operations.serializers import FollowSerializer
from users.models import UserInfo


@permission_classes([permissions.IsAuthenticated])
class FollowAPIView(GenericViewSet,
                    mixins.CreateModelMixin,
                    mixins.UpdateModelMixin):
    queryset = UserInfo.objects.all()
    serializer_class = FollowSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        action = self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        return Response(data={
            'success': True,
            'code': 201,
            'user': self.request.user.id,
            'msg': '成功关注' if action == 'create' else '取消关注',
            'target_user': serializer.data['follow']
        }, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        return serializer.save()
